let app=getApp()
const db=wx.cloud.database()
const shop=db.collection('shop')
const shopComment=db.collection('shopComment')
const _=db.command
const user=db.collection('user')
const formateTime=require('../../utils/formatTime')

Page({
    data:{
        display:true,
        zan_:'zan',
        cai_:'cai',
        img:'',
        name:'',
        start:0,
        localtion:1,
        changing:false,
        getting:false,
        skip:0,
        comment:[],
        footerHeight:0,
        plLoad:true,
        all:{},
        isShow:false
    },
    async onLoad(e){
        wx.showLoading({
          title: '加载店铺信息',
        })
        //获取设备安全区域以设置发言输入框的正确高度
        let info=await wx.getSystemInfo()
        console.log('info',info)
        let footerHeight=info.safeArea.top+56
        this.setData({
            footerHeight
        })
        console.log(app.globalData.nickName)
        console.log('e',e)
        let res=await shop.where({//获取店铺信息
            _id:e.id
        }).get()
        console.log('get',res)
        let openid=app.globalData.openid
        let {all,name,img,start,localtion,zan,cai}=res.data[0]
        //根据点赞数量排序出热门菜品
        let hot=all.slice(0,5)
        hot.sort(function(x,y){
            return y[1].length-x[1].length
        })
        console.log('排序',hot)
        res=await shopComment.where({//加载评论数量
            shop_id:e.id
        })
        .count()
        let commentNum=res.total
        let plLoad=true
        if(commentNum==0){
            plLoad=false
        }
        console.log('comment',commentNum)
        this.setData({
            hot,
            all,
            name,
            start,
            localtion,
            img,
            zan,
            cai,
            _id:e.id,
            openid,
            commentNum,
            plLoad,
            isShow:true
        })
        
        //判断点赞情况↓↓↓
        if(zan.indexOf(app.globalData.openid)>-1){
            this.setData({
                zan_:'_zan'
            })
        }else if(cai.indexOf(app.globalData.openid)>-1){
            this.setData({
                cai_:'_cai'
            })
        }
        let zanList=new Array(all.length)
        for(let i=0;i<all.length;i++){
            if(all[i][1].indexOf(app.globalData.openid)>-1){
                zanList[i]=true
            }
        }
        this.setData({
            zanList
        })
        wx.hideLoading()
    },
    
    checkLogin(){//检查登陆
        let openid=app.globalData.openid
        let that=this
        if(!openid){
            console.log('未登陆')
            wx.showModal({
                title:'你还未登陆',
                content:'请先登陆',
                cancelText:'取消',
                confirmText:'登陆',
                success(res){
                    if(res.confirm){
                        console.log('点了确定')
                        that.login()
                    }
                }
            })
            return false
        }else{
            console.log('已登陆')
            return true
        }
    },
    async login(){//登陆
        console.log(app.globalData.nickName)
        let _id=this.data._id
        let res=await wx.getUserProfile({
          desc: 'desc',
        })
        console.log('res:',res)
        let {avatarUrl,nickName}=res.userInfo      
        res=await wx.cloud.callFunction({
          name:'login',
          data:{
            avatarUrl,nickName
          }
        })
        console.log('登陆结果',res)
        if(res.result.nickName){
          wx.showToast({
            title: '登陆成功',
          })
          let openid= await user.where({
            nickName:nickName,
            avatarUrl:avatarUrl
          })
          .get()
          openid=openid.data[0].openid
          console.log('openid',openid)
          //写入用户数据到客户端↓↓↓
          this.setData({
            avatarUrl:res.result.avatarUrl,
            nickName:res.result.nickName,
            openid
          })
          wx.setStorage({
            key:'user',
            data:{'avatarUrl':avatarUrl,'nickName':nickName,'openid':openid}
          })
          app.globalData.avatarUrl=avatarUrl
          app.globalData.nickName=nickName
          app.globalData.openid=openid
          console.log(app.globalData.nickName)
          console.log(app.globalData.openid)
          wx.redirectTo({
            url: '/pages/orther/content?id='+_id,
          })
        }else{
          wx.showToast({
            title: '登陆失败',
            icon:'error'
          })
        }
      },
    zan(e){//菜品点赞
        let res=this.checkLogin()
        if(!res){
            return
        }
        console.log('e',e)
        //禁止频繁操作
        let changing=this.data.changing
        if(changing){
            wx.showToast({
              title: '请不要频繁操作',
              icon:'error'
            })
            return
        }else{
            this.setData({
                changing:true
            })
        }
        
        let index=e.currentTarget.dataset.index
        let all=this.data.all
        let zanList=this.data.zanList
        let change=true
        let openid=app.globalData.openid
        if(all[index][1].indexOf(openid)>-1){//判断点赞还是取消点赞
            change=false
            console.log('取消点赞')
        }
        wx.cloud.callFunction({
            name:'changeListZan',
            data:{
                _id:this.data._id,
                index,
                change
            }
        })
        if(change){//更新本地点赞数据
            zanList[index]=true
            all[index][1].push(openid)
        }else{
            zanList[index]=false
            all[index][1].pop()
        }
        this.setData({//更新本地点赞数据，并允许继续操作
            zanList,all,changing:false
        })
    },
    shopZan(e){//店铺点赞
        let res=this.checkLogin()
        if(!res){
            return
        }
        console.log(e)
        //禁止频繁操作
        let changing=this.data.changing
        if(changing){
            wx.showToast({
              title: '请不要频繁操作',
              icon:'error'
            })
            return
        }else{
            this.setData({
                changing:true,
            })
        }
        
        let change=true,up=true
        let openid=app.globalData.openid
        if(e.currentTarget.dataset.up=='false'){
            up=false
            if(this.data.cai.indexOf(openid)>-1){
                change=false
            }
        }else if(this.data.zan.indexOf(openid)>-1){
                change=false
        }
        wx.cloud.callFunction({
            name:'changeShopZan',
            data:{
                up,
                _id:this.data._id,
                openid,
                change
            }
        }).then(res=>{//更新本地点赞数据
            this.setData({
                isShow:false
            })
            let zan_,cai_
            let {zan,cai}=this.data
            if(up){//点赞
                if(change){
                    zan_='_zan'
                    zan.push(openid)
                    if(cai.indexOf(openid)>-1){
                        cai.splice(cai.indexOf(openid),1)
                        cai_='cai'
                    }
                }else{//取消点赞
                    zan_='zan'
                    zan.splice(zan.indexOf(openid),1)
                }
            }else{
                if(change){
                    console.log('踩')
                    cai_='_cai'
                    cai.push(openid)
                    if(zan.indexOf(openid)>-1){
                        zan.splice(zan.indexOf(openid),1)
                        zan_='zan'
                    }
                }else{
                    console.log('取消踩')
                    cai_='cai'
                    cai.splice(cai.indexOf(openid),1)
                }
            }
            this.setData({//更新本地点赞数据，并允许继续操作
                zan_,cai_,zan,cai,changing:false,isShow:true
            })
        })
    },
    xq(){
        this.setData({
            display:true
        })
    },
    dp(){
        this.loadComment()
        this.setData({
            plLoad:false,display:false
        })
    },
    async loadComment(load){//加载评论
        if(!this.data.plLoad){
            return
        }
        wx.showLoading({
          title: '加载评论',
        })
        let {getting,skip,_id}=this.data
        if(getting){
            wx.showToast({
              title: '请勿频繁操作',
              icon:'error'
            })
            return
        }else{
            this.setData({
                getting:true
            })
        }
        console.log(_id)
        let res=await shopComment.where({
            shop_id:_id
        }).orderBy('time','desc')
        .skip(skip)
        .limit(10)
        .get()
        
        console.log('comment',res.data)
        let comment=this.data.comment
        console.log('push前',comment)
        for(let i=0;i<10;i++){
            if(!res.data[i]){
                break
            }
            let temp=res.data[i]
            temp.time=formateTime.formatTime(temp.time)
            comment.push(temp)
            console.log('push完',comment)
        }
            console.log('拼接后',comment)
        this.setData({
            comment,
            getting:false,
        })
        let dpZanList=new Array(comment.length)
        let openid=app.globalData.openid
        for(let i=0;i<comment.length;i++){
            if(comment[i].zan.indexOf(openid)>-1){
                dpZanList[i]=true
            }
        }
        this.setData({
            dpZanList
        })
        wx.hideLoading()
    },
    input(e){
        this.setData({
            input:e.detail.value
        })
    },
    commentZan(e){//评论点赞
        let res=this.checkLogin()
        if(!res){
            return
        }
        console.log('评论点赞',e)
        let {comment,dpZanList,changing}=this.data
        if(changing){
            wx.showToast({
              title: '请勿频繁操作',
              icon:'error'
            })
            return
        }
        changing=true
        this.setData({
            changing
        })
        let up=true
        let openid=app.globalData.openid
        let {_id,index}=e.currentTarget.dataset
        if(comment[index].zan.indexOf(openid)>-1){//判断点赞还是取消点赞
            up=false
            comment[index].zan.shift()
            dpZanList[index]=false
            console.log('取消点赞')
        }else{
            comment[index].zan.push(openid)
            dpZanList[index]=true
        }
        wx.cloud.callFunction({
            name:'addShopCommentZan',
            data:{
                _id,up
            }
        }).then(res=>{
            changing=false
            this.setData({
                changing
            })
        })
        this.setData({
            dpZanList,comment,changing
        })
    },
    async send(e){//发送评论
        let res=this.checkLogin()
        if(!res){
            return
        }
        console.log('评论',e)
        let content=e.detail.value
        if(content.length<1){
            wx.showToast({
              title: '请不要发送空消息',
              icon:'error'
            })
            return
        }
        wx.showLoading({
          title: '发表中',
        })
        let {commentNum,_id}=this.data
        let {nickName,avatarUrl}=app.globalData
        console.log(nickName,avatarUrl)
        let time=new Date()
        time=formateTime.formatTime(time)
        console.log('日期',time)
        res=await wx.cloud.callFunction({
            name:'addShopComment',
            data:{
                _id,nickName,avatarUrl,content
            }
        })
        let title='',icon='success'
        if(res.result){
            title='评论成功'
            let comment=this.data.comment
            console.log('comment',comment)
            let arr={avatarUrl: avatarUrl,
            content: content,
            nickName: nickName,
            openid: this.data.openid,
            shop_id: _id,
            time: time,
            zan: [],
            _id: "17e2426e6hcb10bd011a19d9203688fy"}
            console.log('arr',arr)
            comment.unshift(arr)
            commentNum++
            this.setData({
                comment,
                inputValue:'',
                commentNum
            })
        }else{
            title='评论失败'
            icon='error'
        }
        wx.showToast({
          title,
          icon
        })
        wx.hideLoading()
    },
    onReachBottom(){
        if(this.data.display){
            return
        }
        let skip=this.data.skip+10
        console.log('页面触底')
        this.setData({
            skip
        })
        this.loadComment(true)
    }
})